//
//  EndWatchDriveJob.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/2/25.
//

import Vapor
import Queues
import FluentKit
struct EndWatchDriveJob: AsyncJob {
    struct Payload: Codable {
        let eventId: String
    }

    func dequeue(_ context: QueueContext, _ payload: Payload) async throws {
        let eventId = payload.eventId
        if let task = try await TaskModel.query(on: context.application.db)
            .filter(\.$id == eventId)
            .first() {
            task.status = 2
            if let currentLocation = try await LocationModel.query(on: context.application.db)
                .filter(\.$deviceID == task.monitoredID)
                .sort(\.$createDate, .descending)
                .first() {
                var locations = task.locationsWhenTaskOccured ?? []
                let newlocation = TaskModel.LocationWhenTaskOccured(latitude: currentLocation.latitude ?? 0, longitude: currentLocation.longitude ?? 0, detail: currentLocation.detail ?? "", date: currentLocation.createDate)
                locations.append(newlocation)
                task.locationsWhenTaskOccured = locations
            }
            try await task.update(on: context.application.db)
            let user = try await UserModel.query(on: context.application.db).filter(\.$id == task.monitoredID).first()
            APNSModel.query(on: context.application.db)
                .group(.or, { builder in
                    builder.filter(\.$deviceID == (user?.id ?? ""))
                    builder.filter(\.$deviceID == task.initiatorID)
                })
                .all()
                .whenSuccess { tokens in
                    context.queue.dispatch(PushJob.self, PushJob.Payload(receivers: tokens.map({$0.token}), eventId: eventId, title: "未达警报", body: "\(user?.name ?? "您的监测对象")在指定时间内未到达指定区域", avatar: user?.avatar ?? "", mutableContent: false))
                        .whenSuccess { _ in
                            
                        }
                }
        }
    }

    func error(_ context: QueueContext, _ error: Error, _ payload: Payload) -> EventLoopFuture<Void> {
        context.application.logger.error("PrintJob failed: \(error.localizedDescription)")
        return context.eventLoop.makeSucceededFuture(())
    }
}
